Post

Replies

Boosts

Views

Activity

Is there a way to hide NavigationView inline title until user scrolls past a certain point
like the title suggests, I'm trying to collapse the navigationView title bar until the user scrolls past the first section (which I'm using as a header). Please see image.  The reason why I can't use SwiftUI's built in NavigationTitle is because I can't put the profile picture in the NavigationTitle. Anyways, once the word "Summary" disappears, I want the navigationView's inline title to appear and say "Summary". I've tried using .onDisappear and .onAppear on the Text("Summary"), but because of the way the navigation bar works, it doesn't trigger until the user scrolls pretty far down the page. I want a solution that: 1] collapses the top bar until the word "Summary" is out of view, then 2] shows the inline title. Thank you! I have a @State var that changes the navigation title: @State var navigationTitle: String = "" And a NavigationTitle that changes: .navigationBarTitle("\(navigationTitle)", displayMode: .inline) And here is my header view: Section { HStack(spacing: 8) { VStack(alignment: .leading, spacing: 5) { Text("\(Date().formatted(date: .abbreviated, time: .omitted))")                 .foregroundColor(Color.secondary) .textCase(.uppercase) .font(.system(size: 13, weight: .medium, design: .default))                     .onAppear {                     navigationTitle = "" } .onDisappear { navigationTitle = "Summary" } Text("Summary") .font(.largeTitle.bold()) .textCase(nil) .foregroundColor(Color.primary) } Spacer() Button { self.showUserProfileModal.toggle() } label: { Image(systemName: "person.crop.circle") .symbolRenderingMode(.palette) .foregroundStyle(.blue, .blue, .white) .background(Color.white) .clipShape(Circle()) .font(.system(size: 37, weight: .light, design: .default))        } } .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))                     .listRowBackground(Color(.systemGroupedBackground)) }
1
0
2k
Feb ’23
Approach for creating bar chart from data
Hello, My app allows users to input each drink they have to track water consumption. These drinks are saved in CoreData. Each entry has the quantity of the drink and the time it was consumed. Now, I want to create a bar graph that shows how much drink was consumed each hour in the current day. I want it to look exactly like the bar graph in the Apple Fitness app (attached), with 24 vertical lines representing each hour of the day of different height depending on how much drink was consumed in the given hour. The issue is, I need to first fetch all the drinks the user consumed in the current day, then separate them into the different hours. I have no idea I should approach this. Out of desperation, I created 24 fetch requests for the different hours and now have 24 values of quantity (one for each hour). But this is extremely tedious and would just get near impossible to manage. The most efficient way to create a bar chart is to have a for each loop and draw lines for each hour, but I don't know how to get the data in a way that would let me do this. Any guidance is appreciated! Thank you!
1
0
581
Jan ’22
CoreData FetchRequest doesn't update view
I have an app that lets users log drinks. Users create CoreData entries that have attributes like drink type and quantity. I have a view that lets users the quantity they have consumed in the current day. This is done using a FetchRequest and a calendar predicate that only fetches entries from the current day. I am using @FetchRequest property wrapper in the view, then initializing it with init() {}. Inside the initializer, I set the predicate, sort descriptors, and use self._todayIntakeEvents ... to set the value for the fetch request variable. Then, each time the view appears, I use .onAppear to sum the quantity of the fetched items by using todayIntakeEvents.map, then using .reduce to sum the array. The problem: when users add drinks with Siri, the drink information doesn't show up when opening the app from background. However, it will appear if I quit and relaunch the app. What I want to happen is for the drink to appear immediately when the user opens the app again. My code for the view: struct TodaySummaryView: View { @Environment(\.managedObjectContext) private var viewContext     @FetchRequest var todayIntakeEvents: FetchedResults<WaterIntakeEvent> init() {         let calendar = Calendar.current         let dateFrom = calendar.startOfDay(for: Date())         let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom)         let predicateTodayEvents = NSPredicate(format: "timeOfConsumption <= %@ AND timeOfConsumption >= %@", dateTo! as CVarArg, dateFrom as CVarArg)         self._todayIntakeEvents = FetchRequest(             entity: WaterIntakeEvent.entity(),             sortDescriptors: [NSSortDescriptor(keyPath: \WaterIntakeEvent.timeOfConsumption, ascending: false)],             predicate: predicateTodayEvents)     } var body: some View { // some UI .onAppear { totalWaterQuantityToday = todayIntakeEvents.map {Int($0.waterQuantity)}             sumOfWaterQuantityToday = totalWaterQuantityToday.reduce(0, +) print(sumOfWaterQuantityToday) // even after Siri creates new CoreData entries, this still prints the quantity from before it added } My code for the Siri Intent Handler: public func handle(intent: LogDrinkIntent, completion: @escaping (LogDrinkIntentResponse) -> Swift.Void) {         let context = PersistenceController.shared.container.viewContext         let newDrink = WaterIntakeEvent(context: context)         newDrink.drinkType = intent.drinkType         newDrink.quantity = intent.quantity as! Float         newDrink.waterQuantity = intent.quantity as! Float         newDrink.timeOfConsumption = Date()         newDrink.id = UUID()         do {             try context.save()             let response = LogDrinkIntentResponse(code: LogDrinkIntentResponseCode.success, userActivity: nil)             completion(response)             print("Successfully saved.")         } catch {             completion(LogDrinkIntentResponse(code: LogDrinkIntentResponseCode.failure, userActivity: nil))             print("Error saving.")         }     } I suspect the problem is not Siri (because the data appears after relaunching the app) but that because I initialized the view with the FetchRequest, it's not responding to changes. Can someone help please?
1
0
1.2k
Jan ’22
Organize CoreData items for use in bar chart
Hello, I am building an app where users can log their water consumption. I want to create a bar chart which displays how much water they are drinking each hour in the current day (from 12 a.m. to 11:59 p.m.). I have a CoreData entity which stores the quantity of water consumed and the time of consumption. The chart will be hours on the x-axis and ounces on the y-axis. To get the desired bar chart, I plan on making a ForEach loop to create 24 vertical lines to represent the water intake each hour, then adjust the height of those lines based on the quantity. In order to do this, I need an array of 24 items, each of which stores the quantity of water and the hour of the day. Something like this: struct waterIntake: Identifiable { var id = UUID() var quantity: CGFloat var hour: Int } My question is: how do I get from a CoreData entity with the quantity of water and time of consumption to this array with hour numbers? Or, can I use the CoreData entity directly in the ForEach loop? Please remember I need some way to add the quantity of all water consumed in a given hour and group it into one quantity per one hour.
0
0
463
Jan ’22
Is there a way to hide NavigationView inline title until user scrolls past a certain point
like the title suggests, I'm trying to collapse the navigationView title bar until the user scrolls past the first section (which I'm using as a header). Please see image.  The reason why I can't use SwiftUI's built in NavigationTitle is because I can't put the profile picture in the NavigationTitle. Anyways, once the word "Summary" disappears, I want the navigationView's inline title to appear and say "Summary". I've tried using .onDisappear and .onAppear on the Text("Summary"), but because of the way the navigation bar works, it doesn't trigger until the user scrolls pretty far down the page. I want a solution that: 1] collapses the top bar until the word "Summary" is out of view, then 2] shows the inline title. Thank you! I have a @State var that changes the navigation title: @State var navigationTitle: String = "" And a NavigationTitle that changes: .navigationBarTitle("\(navigationTitle)", displayMode: .inline) And here is my header view: Section { HStack(spacing: 8) { VStack(alignment: .leading, spacing: 5) { Text("\(Date().formatted(date: .abbreviated, time: .omitted))")                 .foregroundColor(Color.secondary) .textCase(.uppercase) .font(.system(size: 13, weight: .medium, design: .default))                     .onAppear {                     navigationTitle = "" } .onDisappear { navigationTitle = "Summary" } Text("Summary") .font(.largeTitle.bold()) .textCase(nil) .foregroundColor(Color.primary) } Spacer() Button { self.showUserProfileModal.toggle() } label: { Image(systemName: "person.crop.circle") .symbolRenderingMode(.palette) .foregroundStyle(.blue, .blue, .white) .background(Color.white) .clipShape(Circle()) .font(.system(size: 37, weight: .light, design: .default))        } } .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))                     .listRowBackground(Color(.systemGroupedBackground)) }
Replies
1
Boosts
0
Views
2k
Activity
Feb ’23
Approach for creating bar chart from data
Hello, My app allows users to input each drink they have to track water consumption. These drinks are saved in CoreData. Each entry has the quantity of the drink and the time it was consumed. Now, I want to create a bar graph that shows how much drink was consumed each hour in the current day. I want it to look exactly like the bar graph in the Apple Fitness app (attached), with 24 vertical lines representing each hour of the day of different height depending on how much drink was consumed in the given hour. The issue is, I need to first fetch all the drinks the user consumed in the current day, then separate them into the different hours. I have no idea I should approach this. Out of desperation, I created 24 fetch requests for the different hours and now have 24 values of quantity (one for each hour). But this is extremely tedious and would just get near impossible to manage. The most efficient way to create a bar chart is to have a for each loop and draw lines for each hour, but I don't know how to get the data in a way that would let me do this. Any guidance is appreciated! Thank you!
Replies
1
Boosts
0
Views
581
Activity
Jan ’22
CoreData FetchRequest doesn't update view
I have an app that lets users log drinks. Users create CoreData entries that have attributes like drink type and quantity. I have a view that lets users the quantity they have consumed in the current day. This is done using a FetchRequest and a calendar predicate that only fetches entries from the current day. I am using @FetchRequest property wrapper in the view, then initializing it with init() {}. Inside the initializer, I set the predicate, sort descriptors, and use self._todayIntakeEvents ... to set the value for the fetch request variable. Then, each time the view appears, I use .onAppear to sum the quantity of the fetched items by using todayIntakeEvents.map, then using .reduce to sum the array. The problem: when users add drinks with Siri, the drink information doesn't show up when opening the app from background. However, it will appear if I quit and relaunch the app. What I want to happen is for the drink to appear immediately when the user opens the app again. My code for the view: struct TodaySummaryView: View { @Environment(\.managedObjectContext) private var viewContext     @FetchRequest var todayIntakeEvents: FetchedResults<WaterIntakeEvent> init() {         let calendar = Calendar.current         let dateFrom = calendar.startOfDay(for: Date())         let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom)         let predicateTodayEvents = NSPredicate(format: "timeOfConsumption <= %@ AND timeOfConsumption >= %@", dateTo! as CVarArg, dateFrom as CVarArg)         self._todayIntakeEvents = FetchRequest(             entity: WaterIntakeEvent.entity(),             sortDescriptors: [NSSortDescriptor(keyPath: \WaterIntakeEvent.timeOfConsumption, ascending: false)],             predicate: predicateTodayEvents)     } var body: some View { // some UI .onAppear { totalWaterQuantityToday = todayIntakeEvents.map {Int($0.waterQuantity)}             sumOfWaterQuantityToday = totalWaterQuantityToday.reduce(0, +) print(sumOfWaterQuantityToday) // even after Siri creates new CoreData entries, this still prints the quantity from before it added } My code for the Siri Intent Handler: public func handle(intent: LogDrinkIntent, completion: @escaping (LogDrinkIntentResponse) -> Swift.Void) {         let context = PersistenceController.shared.container.viewContext         let newDrink = WaterIntakeEvent(context: context)         newDrink.drinkType = intent.drinkType         newDrink.quantity = intent.quantity as! Float         newDrink.waterQuantity = intent.quantity as! Float         newDrink.timeOfConsumption = Date()         newDrink.id = UUID()         do {             try context.save()             let response = LogDrinkIntentResponse(code: LogDrinkIntentResponseCode.success, userActivity: nil)             completion(response)             print("Successfully saved.")         } catch {             completion(LogDrinkIntentResponse(code: LogDrinkIntentResponseCode.failure, userActivity: nil))             print("Error saving.")         }     } I suspect the problem is not Siri (because the data appears after relaunching the app) but that because I initialized the view with the FetchRequest, it's not responding to changes. Can someone help please?
Replies
1
Boosts
0
Views
1.2k
Activity
Jan ’22
Organize CoreData items for use in bar chart
Hello, I am building an app where users can log their water consumption. I want to create a bar chart which displays how much water they are drinking each hour in the current day (from 12 a.m. to 11:59 p.m.). I have a CoreData entity which stores the quantity of water consumed and the time of consumption. The chart will be hours on the x-axis and ounces on the y-axis. To get the desired bar chart, I plan on making a ForEach loop to create 24 vertical lines to represent the water intake each hour, then adjust the height of those lines based on the quantity. In order to do this, I need an array of 24 items, each of which stores the quantity of water and the hour of the day. Something like this: struct waterIntake: Identifiable { var id = UUID() var quantity: CGFloat var hour: Int } My question is: how do I get from a CoreData entity with the quantity of water and time of consumption to this array with hour numbers? Or, can I use the CoreData entity directly in the ForEach loop? Please remember I need some way to add the quantity of all water consumed in a given hour and group it into one quantity per one hour.
Replies
0
Boosts
0
Views
463
Activity
Jan ’22